import React, { useEffect, useState } from 'react';
import TREcharts from './TREcharts.js';
import { Modal, Button } from 'antd';
import { useClickAway } from 'ahooks';
import TRNotification from '#/utils/notification.js';
import planIcon from '@/assets/img/plan_icon.png';
import type { IDataListType } from '../../../type';
import { isDark } from '#/utils/utils.js';
import CheckAll from './checkAll.svg';
import styles from './index.less';

interface IProps {
  /**
   * 数据
   */
  data: IDataListType[];
  /**
   * 是否编辑
   */
  isEdit: boolean;
  /**
   * 确认引用
   */
  onSubmit?: (data: any) => void;
  onPress: (data: Record<string, any>) => void;
}

const ChartsForecastComponent = (props: IProps) => {
  const { data, isEdit = true, onPress, onSubmit } = props;
  const [visible, setVisible] = useState<boolean>(true);
  const [check, setCheck] = useState<boolean>(false);
  const [loading, setLoading] = useState<boolean>(false);
  const [curveDataList, setCurveDataList] = useState<IDataListType[]>([]);

  useEffect(() => {
    if (data) {
      setCurveDataList(data);
    }
  }, [data]);

  const _onCancel = () => {
    setVisible(false);
    onPress({ index: 0 });
  };

  // 编辑数据
  const onEdit = (val: any) => {
    setCurveDataList(val);
  };

  const _onSubmit = async () => {
    setLoading(true);
    const _curveDataList = curveDataList.map((item) => ({
      ...item,
      fixedValue:
        item?.fixedValue || item?.fixedValue === 0
          ? Number(item?.fixedValue).toFixed(3)
          : Number(item?.maxValue).toFixed(3),
    }));
    onSubmit && onSubmit(_curveDataList);
    setLoading(false);
    setVisible(false);
    onPress({ index: 1 });
  };

  useClickAway(() => {
    if (check) {
      setCheck(false);
    }
  }, [() => document.getElementById('ahClickAway'), () => document.getElementById('ahClickAway2')]);

  const footerRender = () => [
    <Button key="dtest1" onClick={_onCancel} loading={loading}>
      取消
    </Button>,
    <Button
      key="dtest2"
      type="primary"
      onClick={_onSubmit}
      loading={loading}
      style={{ marginLeft: 16 }}
    >
      确定
    </Button>,
  ];

  return (
    <Modal
      className={styles.modal}
      centered
      width={1200}
      maskClosable={false}
      visible={visible}
      title={
        <div className={styles.titleDiv}>
          <div className={styles.left}>
            <img src={planIcon} className={styles.titleLogo} />
            <span className={styles.title}>图形化策略调整</span>
          </div>
        </div>
      }
      onCancel={_onCancel}
      footer={footerRender()}
    >
      <div className={styles.container}>
        <div
          style={{
            height: '100%',
            width: '100%',
            color: isDark() ? 'rgba(216, 220, 230, 0.4)' : '',
            padding: '0 0',
            position: 'relative',
          }}
        >
          {isEdit && (
            <div
              onClick={() => {
                setCheck(!check);
              }}
              id="ahClickAway2"
              className={`${check ? styles.pitchPerCent : ''} ${styles.perCent}`}
            >
              <img src={CheckAll} width={16} height={16} style={{ marginRight: 8 }} />
              <span>多选</span>
            </div>
          )}
          <TREcharts
            capData={data.map((item) => item?.maxValue)}
            dataList={curveDataList}
            setDataFn={onEdit}
            isEdit={isEdit}
            check={check}
          />
        </div>
      </div>
    </Modal>
  );
};

class ChartsForecast {
  __key__ = '';

  show = (props: any) => {
    return new Promise((resolve) => {
      if (this.__key__ !== '') return;
      this.__key__ = String(Date.now());
      TRNotification.add({
        key: this.__key__,
        content: (
          <ChartsForecastComponent
            {...props}
            onPress={(result: any) => {
              TRNotification.remove(this.__key__);
              this.__key__ = '';
              resolve(result);
            }}
          />
        ),
        duration: null,
        dismiss: this.dismiss,
      });
    });
  };

  dismiss = () => {
    if (this.__key__.length > 0) {
      TRNotification.remove(this.__key__);
      this.__key__ = '';
    }
  };
}

export default new ChartsForecast();
